package api

import (
	"go_iot/apps/base"
	"go_iot/apps/response"
	"go_iot/apps/system/entity"
	"go_iot/pkg/util"

	"github.com/kataras/iris/v12"
)

type LoginClient struct {
	Account  string `json:"account"`
	Password string `json:"password"`
}

func InitRouter(iris *iris.Application) {
	client := iris.Party("/client")
	{
		client.Get("/captcha")
		client.Post("/login", clientLogin)
		client.Post("/register", clientRegister)
		client.Get("/logout")
		client.Get("/code")
	}

	system := iris.Party("/system")
	{
		system.Post("/login")
		system.Get("/logout")
	}
}

func clientRegister(ctx iris.Context) {
	var user entity.User
	if err := ctx.ReadJSON(&user); err != nil {
		response.JsonError(ctx, err)
		return
	}
	user.Salt = util.GetRandStr(6)
	user.HashPassword = util.GetHashPassword(user.Password + user.Salt)

	if err := base.CreateItem(&user); err != nil {

		response.JsonError(ctx, err)
		return
	}
	response.JsonMsg(ctx, "成功")
}

func clientLogin(ctx iris.Context) {

	var u = LoginClient{}
	if err := ctx.ReadJSON(&u); err != nil {
		response.JsonError(ctx, err)
		return
	}

	user, err := entity.CheckUser(u.Account, u.Password)
	if err != nil {
		response.JsonError(ctx, err)
		return
	}
	//生成token
	token, err1 := util.CreateToken(user.ID, user.Account, "main", 0)
	if err1 != nil {

		response.JsonError(ctx, err1)
		return
	}
	m := iris.Map{
		"token": token,
		"user":  user,
	}
	response.JsonSuccess(ctx, m)
}
